package com.bjsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bjsxt.domain.AccountTbl;
import com.bjsxt.mapper.AccountTblMapper;
import com.bjsxt.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountTblMapper accountTblMapper ;

    private static Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class) ;


    @Transactional
    @Override
    public void debit(String userId, int money) {
        logger.info("开始扣减用户：{}的余额，数量为:{}",userId ,money);
        //1 查询数据库里面的账户
        AccountTbl accountTbl = accountTblMapper.selectOne(new LambdaQueryWrapper<AccountTbl>().
                eq(AccountTbl::getUserId, userId));
        if(accountTbl==null){
            throw new IllegalArgumentException("此账号不存在")  ;
        }
        //2 扣减的操作
        int idleMoney = accountTbl.getMoney() - money ;

        // 3 库存的校验
        if(idleMoney<0){
            throw new RuntimeException("库存不足") ;
        }
        //4 设置到账户里面
        accountTbl.setMoney(idleMoney);

        //5 保存到数据库里里面
        accountTblMapper.updateById(accountTbl) ;

        if("SXT_USER_2".equals(userId)){
            throw new RuntimeException("不想成功") ;
        }

    }
}
